import { Controller } from "egg";

export default class RoleController extends Controller {
  public async index() {
    const { ctx } = this;
    const res = await ctx.service.role.findList();
    ctx.helper.success({ ctx, res });
  }

  public async show() {
    const { ctx } = this;
    const { id } = ctx.params;
    const res = await ctx.service.role.selectRolePrivileges(id);
    if (!res) {
      return ctx.helper.error({ ctx, errorType: "commonAlreadyExists" });
    }
    ctx.helper.success({ ctx, res });
  }

  public async create() {
    const { ctx, service } = this;
    const { role_name } = ctx.request.body;
    const data = await service.role.findByName(role_name);
    if (data) {
      return ctx.helper.error({ ctx, errorType: "commonAlreadyExists" });
    }
    const res = await service.role.add(ctx.request.body);
    ctx.helper.success({ ctx, res });
  }

  public async groupAdd() {
    const { ctx, service } = this;
    const { role_group_name } = ctx.request.body;
    const data = await service.role.groupFindByName(role_group_name);
    if (data) {
      return ctx.helper.error({ ctx, errorType: "commonAlreadyExists" });
    }
    const res = await service.role.groupAdd(ctx.request.body);
    ctx.helper.success({ ctx, res });
  }

  public async update() {
    const { ctx } = this;
    const { id } = ctx.params;
    const res = await ctx.service.role.update(id, ctx.request.body);
    ctx.helper.success({ ctx, res });
  }
}
